<template>
	<view class="body">
		<h2>更改昵称</h2>
		<input class="uni-input" focus placeholder="输入昵称" v-model="name"/>
		<view @click="submit()">
			<zy-button class="button" :content="buttonContent"></zy-button>
		</view>
		<uni-popup ref="popup" type="message">
		    <uni-popup-message :type="popup.type" :message="popup.message" :duration="popup.duration"></uni-popup-message>
		</uni-popup>
		<uni-popup ref="borad" type="dialog">
		    <uni-popup-dialog type="base" :title="borad.title" :content="borad.message" :duration="2000" :before-close="true" @confirm="confirm" @close="close"></uni-popup-dialog>
		</uni-popup>
	</view>
</template>

<script>
	import button from '../components/zy-button.vue'
	export default{
		data(){
			return {
				name:"",
				buttonContent:"点击更改",
				namePrev:"",
				popup:{
					type:'success',
					message:'成功',
					duration:2000
				},
				borad:{
					title:'',
					message:''
				}
			}
		},
		onLoad(options){
			this.name = options.name;
		},
		components:{
			'zy-button':button
		},
		methods:{
			async confirm(done){
				let result = await this.submitForm();
				this.popup.message = '修改成功!';
				this.popup.type = "success";
				this.$refs.popup.open();
				setTimeout(()=>{
					uni.switchTab({
						url:'./index'
					})
				},2000);
				done();
			},
			close(done){
				done();
			},
			submit(){
				this.borad.title="提示";
				this.borad.message="确认更改吗?";
				this.$refs.borad.open();
			},
			async submitForm(){
				if(this.name==''){
					this.popup.message = '输入不能为空哦';
					this.popup.type = 'warn';
					this.$refs.popup.open();
				} else {
					let key = uni.getStorageSync('libilibiUserKey');
					let userBag = uni.getStorageSync('libilibiUserBag');
					let result = await uni.request({
						url:this.config.serverUrl+"/mine/changeName",
						method:'POST',
						data:{
							userId:key.userId,
							token:key.token,
							name:this.name
						}
					});
					if(result[1].data.status){
						userBag.name = this.name;
						uni.setStorage({
							key:'libilibiUserBag',
							data:userBag
						})
						return Promise.resolve(true);
					} else {
						this.popup.message = result[1].data.content;
						this.popup.type = 'warn';
						this.$refs.popup.open();
						return Promise.resolve(false);
					}
				}				
			}
		}
	}
</script>

<style lang="scss">
	.body{
		width:100%;
		height:100vh;
		background-color:rgba(0,0,0,0.75);
		>h2{
			color:white;
			text-align: center;
		}
		.button{
			width:240px;
			margin:5px auto;
		}
		input{
			width:60%;
			margin:30px auto;
			border-bottom:1px solid white;
			color:white;
			font-size:26px;
		}
		
	}
</style>
